
import camera from '@ohos.multimedia.camera';
import { BusinessError } from '@ohos.base';
import common from '@ohos.app.ability.common';
import image from '@ohos.multimedia.image';
import fs from '@ohos.file.fs';
import PhotoAccessHelper from '@ohos.file.photoAccessHelper';
import { Context } from '@kit.AbilityKit';

/**
 * 获取cameraManager对象
 * */
export function getCameraManager(context: common.BaseContext): camera.CameraManager {
  let cameraManager: camera.CameraManager = camera.getCameraManager(context);
  return cameraManager;
}

/***
 * 获取当前设备支持的相机列表，列表中存储了设备支持的所有相机ID。
 * 若列表不为空，则说明列表中的每个ID都支持独立创建相机对象；
 * 否则，说明当前设备无可用相机，不可继续后续操作。
 * */
export function getCameraDevices(cameraManager: camera.CameraManager): Array<camera.CameraDevice> {
  let cameraArray: Array<camera.CameraDevice> = cameraManager.getSupportedCameras();
  if (cameraArray != undefined && cameraArray.length > 0) {
    for (let index = 0; index < cameraArray.length; index++) {
      console.info('cameraId : ' + cameraArray[index].cameraId);  // 获取相机ID
      console.info('cameraPosition : ' + cameraArray[index].cameraPosition);  // 获取相机位置
      console.info('cameraType : ' + cameraArray[index].cameraType);  // 获取相机类型
      console.info('connectionType : ' + cameraArray[index].connectionType);  // 获取相机连接类型
    }
    return cameraArray;
  } else {
    console.error("cameraManager.getSupportedCameras error");
    return [];
  }
}

/**
 * 获取当前设备支持的所有输出流，如预览流、拍照流等
 * */
export async function getSupportedOutputCapability(cameraDevice: camera.CameraDevice, cameraManager: camera.CameraManager, sceneMode: camera.SceneMode): Promise<camera.CameraOutputCapability | undefined> {
  // 创建相机输入流
  let cameraInput: camera.CameraInput | undefined = undefined;
  try {
    cameraInput = cameraManager.createCameraInput(cameraDevice);
  } catch (error) {
    let err = error as BusinessError;
    console.error('Failed to createCameraInput errorCode = ' + err.code);
  }
  if (cameraInput === undefined) {
    return undefined;
  }
  // 监听cameraInput错误信息
  cameraInput.on('error', cameraDevice, (error: BusinessError) => {
    console.error(`Camera input error code: ${error.code}`);
  });
  // 打开相机
  await cameraInput.open();
  // 获取相机设备支持的输出流能力
  let cameraOutputCapability: camera.CameraOutputCapability = cameraManager.getSupportedOutputCapability(cameraDevice, sceneMode);
  if (!cameraOutputCapability) {
    console.error("cameraManager.getSupportedOutputCapability error");
    return undefined;
  }
  console.info("outputCapability: " + JSON.stringify(cameraOutputCapability));
  return cameraOutputCapability;
}

/**
 * 在相机应用开发过程中，可以随时监听相机状态，包括新相机的出现、相机的移除、相机的可用状态。
 * 在回调函数中，通过相机ID、相机状态这两个参数进行监听，如当有新相机出现时，
 * 可以将新相机加入到应用的备用相机中
 * */
function onCameraStatus(cameraManager: camera.CameraManager): void {
  cameraManager.on('cameraStatus', (err: BusinessError, cameraStatusInfo: camera.CameraStatusInfo) => {
    console.info(`camera: ${cameraStatusInfo.camera.cameraId}`);
    console.info(`status: ${cameraStatusInfo.status}`);
  });
}
/**
 * 创建拍照输出流
 * */
function getPhotoOutput(cameraManager: camera.CameraManager, cameraOutputCapability: camera.CameraOutputCapability): camera.PhotoOutput | undefined {
  let photoProfilesArray: Array<camera.Profile> = cameraOutputCapability.photoProfiles;//获取当前设备支持的拍照输出流
  if (!photoProfilesArray) {
    console.error("createOutput photoProfilesArray == null || undefined");
  }
  let photoOutput: camera.PhotoOutput | undefined = undefined;
  try {
    photoOutput = cameraManager.createPhotoOutput(photoProfilesArray[0]);
  } catch (error) {
    let err = error as BusinessError;
    console.error(`Failed to createPhotoOutput. error: ${JSON.stringify(err)}`);
  }
  return photoOutput;
}

/**
 * 设置拍照photoAvailable的回调，并将拍照的buffer保存为图片
 * */
async function savePicture(context:Context,buffer: ArrayBuffer, img: image.Image) {
  let photoAccessHelper: PhotoAccessHelper.PhotoAccessHelper = PhotoAccessHelper.getPhotoAccessHelper(context);
  let options: PhotoAccessHelper.CreateOptions = {
    title: Date.now().toString()
  };
  let photoUri: string = await photoAccessHelper.createAsset(PhotoAccessHelper.PhotoType.IMAGE, 'jpg', options);
  //createAsset的调用需要ohos.permission.READ_IMAGEVIDEO和ohos.permission.WRITE_IMAGEVIDEO的权限
  let file: fs.File = fs.openSync(photoUri, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
  await fs.write(file.fd, buffer);
  fs.closeSync(file);
  img.release();
}

function setPhotoOutputCb(context:Context,photoOutput: camera.PhotoOutput) {
  //设置回调之后，调用photoOutput的capture方法，就会将拍照的buffer回传到回调中
  photoOutput.on('photoAvailable', (errCode: BusinessError, photo: camera.Photo): void => {
    console.info('getPhoto start');
    console.info(`err: ${JSON.stringify(errCode)}`);
    if (errCode || photo === undefined) {
      console.error('getPhoto failed');
      return;
    }
    let imageObj: image.Image = photo.main;
    imageObj.getComponent(image.ComponentType.JPEG, (errCode: BusinessError, component: image.Component): void => {
      console.info('getComponent start');
      if (errCode || component === undefined) {
        console.error('getComponent failed');
        return;
      }
      let buffer: ArrayBuffer;
      if (component.byteBuffer) {
        buffer = component.byteBuffer;
      } else {
        console.error('byteBuffer is null');
        return;
      }
      savePicture(context,buffer, imageObj);
    });
  });
}
/**
 * 配置相机的参数可以调整拍照的一些功能，包括闪光灯、变焦、焦距等
 * */
function configuringSession(photoSession: camera.PhotoSession): void {
  // 判断设备是否支持闪光灯
  let flashStatus: boolean = false;
  try {
    flashStatus = photoSession.hasFlash();
  } catch (error) {
    let err = error as BusinessError;
    console.error(`Failed to hasFlash. error: ${JSON.stringify(err)}`);
  }
  console.info(`Returned with the flash light support status: ${flashStatus}`);
  if (flashStatus) {
    // 判断是否支持自动闪光灯模式
    let flashModeStatus: boolean = false;
    try {
      let status: boolean = photoSession.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO);
      flashModeStatus = status;
    } catch (error) {
      let err = error as BusinessError;
      console.error(`Failed to check whether the flash mode is supported. error: ${JSON.stringify(err)}`);
    }
    if (flashModeStatus) {
      // 设置自动闪光灯模式
      try {
        photoSession.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO);
      } catch (error) {
        let err = error as BusinessError;
        console.error(`Failed to set the flash mode. error: ${JSON.stringify(err)}`);
      }
    }
  }
  // 判断是否支持连续自动变焦模式
  let focusModeStatus: boolean = false;
  try {
    let status: boolean = photoSession.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO);
    focusModeStatus = status;
  } catch (error) {
    let err = error as BusinessError;
    console.error(`Failed to check whether the focus mode is supported. error: ${JSON.stringify(err)}`);
  }
  if (focusModeStatus) {
    // 设置连续自动变焦模式
    try {
      photoSession.setFocusMode(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO);
    } catch (error) {
      let err = error as BusinessError;
      console.error(`Failed to set the focus mode. error: ${JSON.stringify(err)}`);
    }
  }
  // 获取相机支持的可变焦距比范围
  let zoomRatioRange: Array<number> = [];
  try {
    zoomRatioRange = photoSession.getZoomRatioRange();
  } catch (error) {
    let err = error as BusinessError;
    console.error(`Failed to get the zoom ratio range. error: ${JSON.stringify(err)}`);
  }
  if (zoomRatioRange.length <= 0 ) {
    return;
  }
  // 设置可变焦距比
  try {
    photoSession.setZoomRatio(zoomRatioRange[0]);
  } catch (error) {
    let err = error as BusinessError;
    console.error(`Failed to set the zoom ratio value. error: ${JSON.stringify(err)}`);
  }
}
/**
 * 通过photoOutput类的capture方法，执行拍照任务。
 * 该方法有两个参数，第一个参数为拍照设置参数的setting，
 * setting中可以设置照片的质量和旋转角度，第二参数为回调函数
 * */
function capture(captureLocation: camera.Location, photoOutput: camera.PhotoOutput): void {
  let settings: camera.PhotoCaptureSetting = {
    quality: camera.QualityLevel.QUALITY_LEVEL_HIGH,  // 设置图片质量高
    rotation: camera.ImageRotation.ROTATION_0,  // 设置图片旋转角度0
    location: captureLocation,  // 设置图片地理位置
    mirror: false  // 设置镜像使能开关(默认关)
  };
  photoOutput.capture(settings, (err: BusinessError) => {
    if (err) {
      console.error(`Failed to capture the photo. error: ${JSON.stringify(err)}`);
      return;
    }
    console.info('Callback invoked to indicate the photo capture request success.');
  });
}
/**
 * previewProfiles获取当前设备支持的预览能力，返回previewProfilesArray数组
 * **/
export function getPreviewOutput(cameraManager: camera.CameraManager, cameraOutputCapability: camera.CameraOutputCapability, surfaceId: string): camera.PreviewOutput | undefined {
  let previewProfilesArray: Array<camera.Profile> = cameraOutputCapability.previewProfiles;
  let previewOutput: camera.PreviewOutput | undefined = undefined;
  try {
    previewOutput = cameraManager.createPreviewOutput(previewProfilesArray[0], surfaceId);
  } catch (error) {
    let err = error as BusinessError;
    console.error("Failed to create the PreviewOutput instance. error code: " + err.code);
  }
  return previewOutput;
}
/***
 * 通过Session.start方法输出预览流，接口调用失败会返回相应错误码
 * */
export async function startPreviewOutput(cameraManager: camera.CameraManager, previewOutput: camera.PreviewOutput): Promise<void> {
  let cameraArray: Array<camera.CameraDevice> = [];
  cameraArray = cameraManager.getSupportedCameras();
  if (cameraArray.length == 0) {
    console.error('no camera.');
    return;
  }
  let cameraInput: camera.CameraInput | undefined = undefined;
  cameraInput = cameraManager.createCameraInput(cameraArray[0]);
  if (cameraInput === undefined) {
    console.error('cameraInput is undefined');
    return;
  }
  // 打开相机
  await cameraInput.open();
  //ohos.multimedia.camera.CameraManager
  let session: camera.CaptureSession = cameraManager.createCaptureSession();
  session.beginConfig();
  session.addInput(cameraInput);
  session.addOutput(previewOutput);
  await session.commitConfig();
  await session.start();
}